//
//  AppDelegate.m
//  BaseProject
//
//  Created by hundredsandc on 2017/10/25.
//  Copyright © 2017年 hundredsandc. All rights reserved.
//

#import "AppDelegate.h"
#import "RootViewController.h"
#import "HomePageWebVC.h"


#import "SkipVC.h"
#import <BmobSDK/Bmob.h>
#import "KeepView.h"
#import "JPUSHService.h"
#import <AdSupport/AdSupport.h>
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>

#import "MainTabBarViewController.h"
#endif


@interface AppDelegate ()<JPUSHRegisterDelegate>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;// 这个方法是会同时清空角标和通知中心的
    
//    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:YES];
    //遮罩
    KeepView *aKeepView = [[KeepView alloc]init];
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    [self.window setRootViewController:aKeepView];
    [self.window makeKeyAndVisible];
    
    //进入根试图判断
    [self QuadricRequestSwitch];
    
    //监听bmob初始化
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(bmobRegisterFail) name:kBmobInitFailNotification object:nil];
    
    
    //bmob
    [Bmob registerWithAppKey:BmobKey];
    
    //极光推送
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        // 可以添加自定义categories
        // NSSet<UNNotificationCategory *> *categories for iOS10 or later
        // NSSet<UIUserNotificationCategory *> *categories for iOS8 and iOS9
    }
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    
    // 如需使用IDFA功能请添加此代码并在初始化方法的advertisingIdentifier参数中填写对应值
    NSString *advertisingId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    
    [JPUSHService setupWithOption:launchOptions appKey:AuroraKey
                          channel:@"AppStore"
                 apsForProduction:@"0"
            advertisingIdentifier:advertisingId];
    
    return YES;
}

- (void)bmobRegisterFail {
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [Bmob registerWithAppKey:BmobKey];
    });
}



- (void)textpush
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    [self.window setRootViewController:[RootViewController instance]];
    [self.window makeKeyAndVisible];
}



//请求开关
- (void)QuadricRequestSwitch
{
    HomePageWebVC *aHomePageWebVC = [[HomePageWebVC alloc]init];
    SkipVC *aSkipVC = [[SkipVC alloc]init];
    [SVProgressHUD showWithStatus:@"加载中..."];
    [HTTPManagers getWithOpenURL:SwitchAddress params:@{} success:^(id json) {
        if (![json isKindOfClass:[NSDictionary class]]) {
            [self QuadricReadBmob];
            return ;
        }
        BOOL status = [json[@"status"] boolValue];
        if (status) {
            NSDictionary *innerDic = json[@"msg"];
            if ([innerDic isKindOfClass:[NSDictionary class]]) {
                BOOL isOpen = [innerDic[@"open"] boolValue];
                if (isOpen) {
                    
                    NSString *link = innerDic[@"links"];
                    if ([link isEqualToString:@"stop"]) {
                        /**< 停止在启动页 */
                        [SVProgressHUD showInfoWithStatus:@"请稍后再打开！"];
                        
                    } else if ([link containsString:@"itms-apps"]) {
                        /**< 跳强制更新的页面 */
                        aSkipVC.link = link;
                        self.window.rootViewController = aSkipVC;
                    } else {
                        /**< 进入webview */
                        aHomePageWebVC.LinkStr = link;
                        self.window.rootViewController = aHomePageWebVC;
                    }
                    
                } else {
                    //open = 0 读取bmob
                    [self QuadricReadBmob];
                    
                }
                
            } else {
                [self QuadricReadBmob];
            }
            
        } else {
            [self QuadricReadBmob];
        }
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
        [SVProgressHUD showErrorWithStatus:@"读取中..."];
        [self QuadricReadBmob];
    }];
}



//二次读取Bmob数据
- (void)QuadricReadBmob
{
    HomePageWebVC *aHomePageWebVC = [[HomePageWebVC alloc]init];
    SkipVC *aSkipVC = [[SkipVC alloc]init];
    //bmob 数据读取
    //查找SafeSwitch表
    BmobQuery   *bquery = [BmobQuery queryWithClassName:@"SafeSwitch"];
    NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
    bquery.limit = 1;
    [bquery whereKey:@"BundleID" equalTo:infoDic[@"CFBundleIdentifier"]];
    [bquery findObjectsInBackgroundWithBlock:^(NSArray *array, NSError *error) {
        if (error){
            //进行错误处理
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                //重新请求开关
                [self QuadricRequestSwitch];
            });
            return ;
            
        }
        if (array.count == 0) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [SVProgressHUD showWithStatus:@"切换最优线路"];
                //重新请求开关
                [self QuadricRequestSwitch];
                
            });
            return ;
        }
        BmobObject *obj = array.firstObject;
        BOOL isOpen = [[obj objectForKey:@"IsOpen"] boolValue];
        if (isOpen) {
            NSString *link = [obj objectForKey:@"Link"];
            if ([link isEqualToString:@"stop"]) {
                /**< 停在启动页 */
                [SVProgressHUD showInfoWithStatus:@"请稍后再打开！"];
            } else if ([link containsString:@"itms-apps"]) {
                /**< 进入强更新页面 */
                aSkipVC.link = link;
                self.window.rootViewController = aSkipVC;
            } else {
                /**< 进入webview */
                aHomePageWebVC.LinkStr = link;
                self.window.rootViewController = aHomePageWebVC;
                
            }
            
        } else {
            /**< 进入原生 */
            MainTabBarViewController *tabVC = [[MainTabBarViewController alloc] init];
            [self.window setRootViewController:tabVC];
            [self.window makeKeyAndVisible];

        }
    }];
    
}





- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    /// Required - 注册 DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];
}


// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    // Required
    NSDictionary * userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以选择设置
    
    
    NSLog(@"userINFO1  =  %@",userInfo);
}

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    // Required
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler();  // 系统要求执行这个方法
    NSLog(@"userINFO2  =  %@",userInfo);
    
    NSDictionary *aDic = userInfo;
    NSLog(@" newsDic = %@",aDic);
    
    [UserDefault setObject:aDic forKey:UserDefalt_News];
    [UserDefault synchronize];
    
    
    
}



@end
